Page({
  data: {
    loading: true,
    submitting: false,
    members: [],
    selectedMemberId: null,
    selectedMemberIndex: 0,
    selectedMemberName: '',
    reminderTypes: [
      { value: 'medication', label: '吃药提醒' },
      { value: 'exercise', label: '运动提醒' },
      { value: 'diet', label: '饮食提醒' },
      { value: 'checkup', label: '体检提醒' },
      { value: 'other', label: '其他提醒' }
    ],
    typeIndex: 0,
    type: 'medication',
    typeLabel: '吃药提醒',
    title: '',
    content: '',
    placeholderText: '例如：每次服用XXX药物1片',
    repeatOptions: [
      { value: 'once', label: '一次性' },
      { value: 'daily', label: '每天' },
      { value: 'weekly', label: '每周' },
      { value: 'monthly', label: '每月' }
    ],
    repeatTypeIndex: 0,
    repeatType: 'once',
    repeatTypeLabel: '一次性',
    showWeekdaySelector: false,
    weekdays: [
      { value: '日', checked: false },
      { value: '一', checked: false },
      { value: '二', checked: false },
      { value: '三', checked: false },
      { value: '四', checked: false },
      { value: '五', checked: false },
      { value: '六', checked: false }
    ],
    selectedWeekdays: [],
    date: '',
    time: '08:00'
  },

  onLoad: function(options) {
    // 如果URL传递了memberId参数，则预选成员
    if (options.memberId) {
      this.setData({
        selectedMemberId: parseInt(options.memberId)
      });
    }
    
    // 设置默认的日期和时间
    const now = new Date();
    const date = now.getFullYear() + '-' + this.formatNumber(now.getMonth() + 1) + '-' + this.formatNumber(now.getDate());
    const time = this.formatNumber(now.getHours()) + ':' + this.formatNumber(now.getMinutes());
    
    this.setData({
      date: date,
      time: time
    });
    
    // 设置默认的提示文本
    this.updatePlaceholderText();
    
    // 加载家庭成员数据
    this.loadMembers();
  },
  
  formatNumber: function(n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  },
  
  // 更新提示文本
  updatePlaceholderText: function() {
    let placeholderText = '请输入提醒详情';
    
    if (this.data.type === 'medication') {
      placeholderText = '请输入药品名称、用量等';
    } else if (this.data.type === 'checkup') {
      placeholderText = '请输入体检地点、注意事项等';
    }
    
    this.setData({ placeholderText });
  },
  
  loadMembers: function() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 输出token信息以便调试
    console.log('使用的认证Token:', token);
    
    this.setData({ loading: true });
    
    wx.request({
      url: 'http://localhost:3000/api/members',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        console.log('成员数据API响应:', res);
        
        if (res.data.success) {
          const members = res.data.data.members || [];
          console.log('获取到的成员列表:', members);
          
          this.setData({
            members: members,
            loading: false
          });
          
          // 如果没有预选成员，默认选择第一个成员
          if (!this.data.selectedMemberId && members.length > 0) {
            this.setData({
              selectedMemberId: members[0].id,
              selectedMemberName: members[0].name
            });
            console.log('自动选择第一个成员:', members[0]);
          } else if (this.data.selectedMemberId) {
            // 如果有预选成员，找到对应的名称和索引
            const selectedMember = members.find(m => m.id === this.data.selectedMemberId);
            const selectedMemberIndex = members.findIndex(m => m.id === this.data.selectedMemberId);
            
            console.log('查找预选成员:', this.data.selectedMemberId);
            console.log('找到的成员:', selectedMember);
            
            if (selectedMember) {
              this.setData({
                selectedMemberName: selectedMember.name,
                selectedMemberIndex: selectedMemberIndex >= 0 ? selectedMemberIndex : 0
              });
            } else {
              console.warn('未找到ID为', this.data.selectedMemberId, '的成员');
              // 如果找不到预选成员，默认选择第一个
              if (members.length > 0) {
                this.setData({
                  selectedMemberId: members[0].id,
                  selectedMemberName: members[0].name,
                  selectedMemberIndex: 0
                });
                console.log('默认选择第一个成员:', members[0]);
              }
            }
          }
        } else {
          console.error('获取家庭成员失败:', res.data.message);
          this.setData({ loading: false });
          wx.showToast({
            title: res.data.message || '获取成员数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  onMemberChange: function(e) {
    const index = parseInt(e.detail.value);
    const member = this.data.members[index];
    
    if (member) {
      this.setData({
        selectedMemberId: member.id,
        selectedMemberIndex: index,
        selectedMemberName: member.name
      });
    }
  },
  
  onTitleInput: function(e) {
    this.setData({
      title: e.detail.value
    });
  },
  
  onContentInput: function(e) {
    this.setData({
      content: e.detail.value
    });
  },
  
  onTypeChange: function(e) {
    const index = parseInt(e.detail.value);
    const type = this.data.reminderTypes[index];
    
    if (type) {
      this.setData({
        type: type.value,
        typeIndex: index,
        typeLabel: type.label
      }, () => {
        // 更新提示文本
        this.updatePlaceholderText();
      });
    }
  },
  
  onDateChange: function(e) {
    this.setData({
      date: e.detail.value
    });
  },
  
  onTimeChange: function(e) {
    this.setData({
      time: e.detail.value
    });
  },
  
  onRepeatTypeChange: function(e) {
    const index = parseInt(e.detail.value);
    const repeatOption = this.data.repeatOptions[index];
    
    if (repeatOption) {
      this.setData({
        repeatType: repeatOption.value,
        repeatTypeIndex: index,
        repeatTypeLabel: repeatOption.label,
        showWeekdaySelector: repeatOption.value === 'weekly'
      });
    }
  },
  
  onWeekdayChange: function(e) {
    const index = e.currentTarget.dataset.index;
    const weekdays = this.data.weekdays;
    weekdays[index].checked = !weekdays[index].checked;
    
    this.setData({
      weekdays: weekdays
    });
  },
  
  submitForm: function() {
    // 表单验证
    if (!this.data.selectedMemberId) {
      wx.showToast({
        title: '请选择家庭成员',
        icon: 'none'
      });
      return;
    }
    
    // 验证所选成员是否在列表中存在
    const memberExists = this.data.members.some(m => m.id === this.data.selectedMemberId);
    if (!memberExists) {
      console.error('选择的成员ID在列表中不存在:', this.data.selectedMemberId);
      console.log('当前成员列表:', this.data.members);
      
      wx.showToast({
        title: '所选成员无效，请重新选择',
        icon: 'none'
      });
      
      // 如果有成员，自动选择第一个
      if (this.data.members.length > 0) {
        this.setData({
          selectedMemberId: this.data.members[0].id,
          selectedMemberName: this.data.members[0].name,
          selectedMemberIndex: 0
        });
      }
      return;
    }
    
    if (!this.data.title.trim()) {
      wx.showToast({
        title: '请输入提醒标题',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.time) {
      wx.showToast({
        title: '请选择提醒时间',
        icon: 'none'
      });
      return;
    }
    
    // 验证提醒类型
    if (!this.data.type) {
      console.error('提醒类型未设置');
      wx.showToast({
        title: '请选择提醒类型',
        icon: 'none'
      });
      return;
    }
    
    // 如果是每周重复，至少选择一天
    if (this.data.repeatType === 'weekly') {
      const hasSelectedDay = this.data.weekdays.some(day => day.checked);
      if (!hasSelectedDay) {
        wx.showToast({
          title: '请至少选择一天',
          icon: 'none'
        });
        return;
      }
    }
    
    // 处理重复值
    let repeatValue = null;
    if (this.data.repeatType === 'weekly') {
      const selectedDays = this.data.weekdays
        .filter(day => day.checked)
        .map(day => day.value);
      repeatValue = selectedDays.join(',');
    }
    
    // 组装请求数据
    const reminderData = {
      member_id: this.data.selectedMemberId,
      title: this.data.title,
      content: this.data.content,
      type: this.data.type,
      remind_time: this.data.time,
      repeat_type: this.data.repeatType,
      repeat_value: repeatValue
    };
    
    // 一次性提醒需要日期
    if (this.data.repeatType === 'once') {
      reminderData.remind_date = this.data.date;
    }
    
    // 输出请求数据进行调试
    console.log('提交的提醒数据:', reminderData);
    console.log('提醒类型:', this.data.type);
    console.log('当前成员列表:', this.data.members);
    console.log('选中的成员ID:', this.data.selectedMemberId);
    
    // 确保type字段存在且有值
    if (!reminderData.type) {
      console.error('提醒类型为空，使用默认值');
      reminderData.type = 'medication'; // 使用默认值
    }
    
    // 提交表单
    this.submitReminder(reminderData);
  },
  
  submitReminder: function(reminderData) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.setData({ submitting: true });
    console.log('发送请求到:', 'http://localhost:3000/api/reminders');
    console.log('请求头:', { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' });
    console.log('请求数据:', reminderData);
    
    wx.request({
      url: 'http://localhost:3000/api/reminders',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: reminderData,
      success: (res) => {
        console.log('API响应:', res);
        this.setData({ submitting: false });
        
        if (res.data && res.data.success) {
          wx.showToast({
            title: '创建提醒成功',
            icon: 'success'
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          console.error('创建提醒失败:', res.data ? res.data.message : '未知错误');
          wx.showToast({
            title: res.data && res.data.message ? res.data.message : '创建提醒失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败详情:', err);
        this.setData({ submitting: false });
        
        // 尝试解析更详细的错误信息
        let errorMsg = '网络错误，请稍后重试';
        if (err.errMsg) {
          if (err.errMsg.includes('404')) {
            errorMsg = 'API接口不存在，请检查服务器是否正常运行';
          } else if (err.errMsg.includes('timeout')) {
            errorMsg = '请求超时，请检查网络连接';
          }
        }
        
        wx.showToast({
          title: errorMsg,
          icon: 'none'
        });
      }
    });
  },
  
  cancel: function() {
    wx.navigateBack();
  },
}) 